//
//  BatchDeptTreePopView.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/12/7.
//

import Foundation
import UIKit

class BatchDeptTreePopView: UIView {
    let headerV = BSSearchButton(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 60))
    let treeTable = BatchDeptTreeTable()
    let resultV = BatchDeptTreeResultView()

    var isResult: Bool = false

    init(withDeptName deptName: String) {
        super.init(frame: .zero)
        backgroundColor = .white
        setupUI()
        reloadData(withDeptName: deptName)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func reloadData(withDeptName deptName: String) {
        showToastActivity()
        API.getDeptTree(withParam: DeptParam(deptName: deptName), block: { responseModel in
            DispatchQueue.main.async {
                self.treeTable.datas = responseModel.models ?? []
                self.hideToastActivity()
            }
        })
    }
    
    @objc func showSearchTapped() {
        isResult = true
        if resultV.superview == nil {
            addSubview(resultV)
            resultV.snp.makeConstraints { make in
                make.top.left.right.equalToSuperview()
                make.bottom.equalTo(treeTable.snp.bottom)
            }
            resultV.resetUI()
        }
    }
    
    @objc func cencelTFTapped() {
        isResult = false
        if resultV.superview != nil {
            resultV.removeFromSuperview()
        }
    }
    
    func setupUI() {
        headerV.titleL.text = "搜索网点"
        headerV.padding = 25
        headerV.addTarget(self, action: #selector(showSearchTapped), for: .touchUpInside)
        addSubview(headerV)
        headerV.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(60)
        }
        
        addSubview(treeTable)
        treeTable.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(headerV.snp.bottom)
            make.bottom.equalTo(self.safeAreaLayoutGuide.snp.bottom)
        }
        
        resultV.headerV.cancelBtn.addTarget(self, action: #selector(cencelTFTapped), for: .touchUpInside)
    }
}
